import org.codehaus.groovy.grails.support.GrailsTestSuite

import java.sql.Connection
import java.sql.DriverManager
import junit.framework.TestResult
import groovy.util.GroovyTestCase

def suites = []
def datasetHome = new File("${basedir}/test/datasets")

def datasetInfo = null

ClassLoader parent = getClass().getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);

loader.parseClass(file("DatasetFilenameFilter.groovy"));

Class dataSetClass = loader.parseClass(file("DataSetInfo.groovy"));

eventTestStart = { GrailsTestSuite suite, GroovyTestCase test, TestResult result ->

	if(!suites.contains(suite.name)) {

        suites << suite.name

		datasetInfo = dataSetClass.newInstance()
	    datasetInfo.forClass(test.class).withDataSetHome(datasetHome)

        datasetInfo?.load getConnection()

	}
}

eventTestEnd = { GrailsTestSuite suite, GroovyTestCase test, TestResult result ->
	info?.unload getConnection()
}

def getConnection() {

    String env = System.getProperty("grails.env")
    env = env ?: 'test'

    URL url = new File("${basedir}/grails-app/conf/DataSource.groovy").toURL()
    def config = new ConfigSlurper(env).parse(url)

    def username    = config.dataSource.username
    def password    = config.dataSource.password
    def databaseUrl = config.dataSource.url
    def driver      = config.dataSource.driverClassName

    Class.forName(driver)

    Connection connection = DriverManager.getConnection(databaseUrl, username, password)
    connection.setAutoCommit true
    return connection

}

def file(name) {
    def result = null
    new File('.').eachFileRecurse { f -> if(f =~ "${name}") result = f }
    return result
}